#!/usr/bin/python
#coding=utf-8

from jinja2 import Environment, FileSystemLoader
from web.session import Session
from igor import logging
from utils.model import md5 

def import_obj(fullname):
    parts = fullname.split('.')
    pkg, classname = '.'.join(parts[:-1]), parts[-1]
    cls = __import__(pkg, None, None, classname, 0)
    return getattr(cls, classname)()

def render(template_name, args=None):
    env = Environment(
            loader = FileSystemLoader("templates"),
            auto_reload = True
    )   
    env.autoescape = True
    template = env.get_template(template_name)
    if args:
        page = template.render(args).encode('utf8')
    else:
        page = template.render().encode('utf8')
    return page

def auth(func):
    def decorator(self, req, resp):
        sid = req.get_cookies().get('sid')
        session = Session(req)
        if not sid:
            return resp.redirect('/login')
        if not session.get('login'):
            resp.clear_cookie('sid')
            return resp.redirect('/login')
        return func(self, req, resp)
    return decorator

def check_login(func):
    def dec(self, req, resp):
        session = Session(req)
        if session.get('login'):
            return resp.redirect('/')
        return func(self, req, resp)
    return dec

def check_token(func):
    def dec(self, req, resp):
        token = req.args.get('token', [''])[0]
        session = Session(req)
        logging.log('token=%s, session_token=%s' %(token, session['token']))
        if token=='' or token != session['token']: 
            return resp.redirect('/login')
        return func(self, req, resp)
    return dec

def set_navbar(req):
    sess = Session(req)
    if sess.get('login'):
        patterns = {'leftbar':'none', 'rightbar':'block', 
                'user': sess['user']}
    else:
        patterns = {'leftbar':'block', 'rightbar': 'none'}
    return patterns

def get_token(req):
    sess = Session(req)
    if sess.get('token'):
        return sess['token']
    else:
        return None 
        
def set_session(req, resp, user):
    sess = Session(req)
    sess['login'] = True
    sess['user'] = user
    logging.log('user.name=%s, user.username=%s' % (user.name, user.username))
    sess['token'] = md5(user.username)
    sess.save()
    resp.set_cookie('sid', sess.sid)

def pager(str_page_no, count, PAGE_SIZE=16):
    try:
        page_no = int(str_page_no)
    except ValueError, err:
        page_no = 1 
    total_pages = (count + PAGE_SIZE -1) / PAGE_SIZE
    if page_no > total_pages or page_no < 1:
        page_no = 1
    if page_no <= 1:
        prev = 1 
    else:
        prev = page_no - 1 
    if page_no >= total_pages:
        next = 1 
    else:
        next = page_no + 1 
    return (page_no, total_pages, prev, next)
